<?php

namespace App\Models;

use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
use EloquentFilter\Filterable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use App\Models\Traits\DataScopeHelper;
use Illuminate\Http\Exceptions\HttpResponseException;




class MiniUser extends Authenticatable implements JWTSubject
{

    use HasApiTokens, HasFactory, Notifiable;

    //模型字段过滤器
    use Filterable;
    use DataScopeHelper;
    protected $dateFormat = 'U';
    protected $table = 'mini_user';
    protected $fillable = [
        'openid',
        'nickname',
        'avatar',
        'sex',
        'session_key',
        'create_by',
        'update_by',
        'appid',

    ];
    public static function boot()
    {
        parent::boot();
        //监听模型创建事件
        static::creating(function ($model) {
            // if ($model->isFillable('create_by')) {
            //     if (!$model->create_by) {
            //         $model->create_by = auth("mini_user")->id() ?? -1;
            //     }
            // }
            if ($model->isFillable('update_by')) {
                // $model->update_by = auth()->id() ?? -1;
                if (!$model->update_by) {
                    $model->update_by = auth("mini_user")->id() ?? -1;
                }
            }
        });
        //监听模型更新之前事件 todo判断数据权限
        static::updating(function ($model) {
            // if ($model->isFillable('create_by')) {
            //     //获取权限范围id
            //     $scope_info = $model->getCreateByIds();
            //     if ($scope_info['scope'] == 'limit' && !in_array($model->create_by, $scope_info['ids'])) {
            //         throw new HttpResponseException(error('非法操作更新数据'));
            //     }
            //     unset($model->attributes['create_by']);
            // }
            //获取当前登录用户ID
            if ($model->isFillable('update_by')) {
                $model->update_by = auth("mini_user")->id() ?? -1;
            }
        });

        //监听模型删除之前事件 todo判断数据权限
        static::deleting(function ($model) {
            if ($model->isFillable('create_by')) {
                //获取权限范围id
                $scope_info = $model->getCreateByIds();
                if ($scope_info['scope'] == 'limit' && !in_array($model->create_by, $scope_info['ids'])) {
                    throw new HttpResponseException(error('非法操作删除数据'));
                }
            }
        });

        //        static::addGlobalScope(new DataFilterScope);
    }
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
